import { defineStore } from 'pinia';
import { store } from '@/store/index';
import { AuthRoute, ConstantRoute } from '@/router';
import type { RouteRecordName, RouteRecordRaw } from 'vue-router';
import { useUserStore } from '@/store/useUserStore';
import { generatorMenu } from '@/utils';
import { ItemType } from 'ant-design-vue';

interface AuthState {
  menus: ItemType[];
  routers: RouteRecordRaw[];
  addRouters: RouteRecordRaw[];
  keepAliveComponents: string[];
  routeGenerated: boolean;
}

export const useAuthStore = defineStore({
  id: 'app-auth',
  state: (): AuthState => ({
    menus: [],
    routers: ConstantRoute,
    addRouters: [],
    keepAliveComponents: [],
    // 动态路由是否已添加
    routeGenerated: false,
  }),
  getters: {
    getMenus(): ItemType[] {
      return this.menus;
    },
    isRouteGenerated(): boolean {
      return this.routeGenerated;
    },
  },
  actions: {
    // 设置动态路由
    setRouters(routers: RouteRecordRaw[]) {
      this.addRouters = routers;
      this.routers = ConstantRoute.concat(routers);
    },
    setMenus(menus: RouteRecordRaw[]) {
      // 设置动态路由
      this.menus = generatorMenu(menus);
    },
    setKeepAliveComponents(compNames: RouteRecordName[]) {
      // 设置需要缓存的组件
      this.keepAliveComponents = compNames;
    },
    setRouteGenerated(added: boolean) {
      this.routeGenerated = added;
    },
    hasPermission(permissions: string[], route: RouteRecordRaw) {
      if (route.meta && route.meta.permissions) {
        return permissions.some((permission) => route.meta.permissions.includes(permission));
      } else {
        return true;
      }
    },
    filterGenerateRoutes(routes: RouteRecordRaw[], permissions: string[]) {
      return routes
        .map((route) => {
          const tmp = { ...route };
          if (this.hasPermission(permissions, tmp)) {
            if (tmp.children) {
              tmp.children = this.filterGenerateRoutes(tmp.children, permissions);
            }
            return tmp;
          }
          return null;
        })
        .filter(Boolean);
    },
    generateRoutes() {
      let userStore = useUserStore();
      let userInfo = userStore.getUserInfo;
      let permissions = userInfo.permissions;
      let routes = AuthRoute;
      let accessedRoutes: RouteRecordRaw[];
      if (permissions?.includes('*')) {
        accessedRoutes = routes || [];
      } else {
        accessedRoutes = this.filterGenerateRoutes(routes, permissions);
      }
      this.setRouters(accessedRoutes);
      this.setMenus(accessedRoutes);
      return accessedRoutes;
    },
  },
});

export function useAuthStoreOut() {
  return useAuthStore(store);
}
